<!-- AdminForm.vue -->
<script setup>
import { ref, watch } from 'vue'
import { addAdmin, updateAdmin } from '@/api/admin'
import { ElMessage } from 'element-plus'

const props = defineProps({
  // 编辑模式时传入的管理员信息（添加模式为 null）
  admin: Object
})
const emit = defineEmits(['success'])

const drawer = ref(false)
const formLabelWidth = '100px'
const form = ref({
  id: null,
  name: '',
  password: ''
})

// 打开抽屉并设置表单数据
const openDrawer = (adminData = null) => {
  drawer.value = true
  if (adminData) {
    // 编辑模式
    form.value = { ...adminData }
  } else {
    // 添加模式
    form.value = { id: null, name: '', password: '' }
  }
}

// 提交表单
const onSubmit = async () => {
  const apiCall = form.value.id ? updateAdmin : addAdmin
  const res = await apiCall(form.value)

  if (res.code === '0') {
    ElMessage.success(res.msg || (form.value.id ? '更新成功' : '添加成功'))
    drawer.value = false
    emit('success') // 通知父组件刷新数据
  } else {
    ElMessage.error(res.msg || '操作失败')
  }
}

// 向父组件暴露方法
defineExpose({ openDrawer })
</script>

<template>
  <el-drawer v-model="drawer" :title="form.id ? '编辑管理员' : '添加管理员'" direction="rtl" size="40%">
    <div class="demo-drawer__content">
      <el-form :model="form">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth">
          <el-button type="primary" @click="onSubmit">{{ form.id ? '更新' : '添加' }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-drawer>
</template>

<style scoped>
.demo-drawer__content {
  padding: 20px;
}
</style>
